package org.xiaojun.loginDemo.controller;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;
import org.xiaojun.loginDemo.pojo.Employee;
import org.xiaojun.loginDemo.service.IEmployeeService;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xj
 * @since 2021-08-07
 */
@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    IEmployeeService employeeService;

    @Value("${photo.file.dir}")
    String photoPath;

    @RequestMapping("/list")
    public String list(Model model){

        List<Employee> employeeList = employeeService.list();

        model.addAttribute("employeeList", employeeList);

        return "employee";
    }

    @RequestMapping("/doAddEmp")
    public String save(Employee employee, MultipartFile img, Model model) throws IOException {

        String fileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String fileNameSuffix = img.getOriginalFilename().substring(img.getOriginalFilename().lastIndexOf("."));
        String newFileName = fileNamePrefix + fileNameSuffix;

        employee.setPhoto(newFileName);
        String result = employeeService.saveEmployee(employee);

        if (StringUtils.isNotBlank(result)){
            model.addAttribute("msg", result);
            return "addEmp";
        }

        img.transferTo(new File(photoPath, newFileName));
        return "redirect:/employee/list";
    }

}
